# -- coding: UTF-8 --
# author: zhanghao
# time: 2023-12-26
# info: 这是配置加载类

import os
import json
import requests

from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.interval import IntervalTrigger

from domain.rule_config import RuleConfig
from config.logger import Logger
from domain.match_config import MatchConfig
from helper.file_helper import FileHelper


class Config:
    logger = Logger.get()

    url = 'http://anbao2.yiweb.com/api/ocr/getRules'
    rule = ""
    rule_file_url = ''
    current_dir = ''
    rule_config: RuleConfig
    scheduler = BackgroundScheduler()

    def __init__(self, url):
        self.url = url
        self.rule_config = RuleConfig()
        self.current_dir = os.getcwd()
        self.logger.info(self.current_dir)

    def initConfig(self):
        self.loadConfig()

        # 启动配置文件更新定时任务
        self.logger.info('启动定时任务')
        trigger = IntervalTrigger(seconds=60)
        self.scheduler.add_job(self.updateConfig, trigger)
        self.logger.info(self.rule_config)
        self.scheduler.start()
        self.logger.info('启动任务成功')

    def updateConfig(self):
        self.logger.info('download updateConfig')
        try:
            response = requests.get(url=self.url, timeout=5)

            self.logger.info(response.status_code)
            if response and response.status_code == 200:
                self.logger.info(response.text)
                match_json = json.loads(response.text)

                rule_path = self.current_dir + '/conf/config.json'
                with open(rule_path, 'r', encoding='utf-8') as f:
                    rule_json = json.load(f)

                self.logger.info('新旧版本号分别为：' + match_json['version'] + ' ' + rule_json['version'])
                # 版本号大才写入
                if FileHelper.versionCompare(match_json['version'], rule_json['version']):
                    with open(rule_path, 'w', encoding='utf-8') as file:
                        json.dump(match_json, file, indent=4, ensure_ascii=False)

                    self.loadConfig()
                    self.logger.info('配置更新成功: ' + str(self.rule))
                else:
                    self.logger.info('配置未发生变化')

        except Exception as e:
            self.logger.exception('更新配置异常', e)

    def loadConfig(self):
        self.logger.info('加载配置.........')
        rule_path = self.current_dir + '/conf/config.json'

        with open(rule_path, 'r', encoding='utf-8') as f:
            rule_json = json.load(f)
        match_config = MatchConfig(rule_json['version'], rule_json['name'], rule_json['rules'])

        self.rule_config.configRules(match_config)

    def getVersion(self):
        return self.rule_config.version
